import _ from 'lodash';
import { history } from 'umi';
import { decryptParams } from '@/utils/crypto';

export const getDecryptData = (data) => {
  const decryptData = _.isString(data) ? decryptParams(data) : data;
  return _.isString(decryptData)
    ? decryptData !== 'null'
      ? JSON.parse(decryptData)
      : null
    : decryptData;
};

export default [
  async (response, requestOpts) => {
    const { status, statusText } = response;
    const { responseType } = requestOpts;
    if (status === 200) {
      if (responseType === 'blob') {
        let fileName;
        try {
          fileName = decodeURI(
            response.clone().headers.get('Content-Disposition').split(';')[1].split('filename=')[1],
          );
        } catch (e) {
          console.log('获取文件名失败');
        }
        const blob = await response.clone().blob();
        return Promise.resolve({ blob, fileName });
      } else {
        const resData = await response.clone().json();
        let errorMessage = resData?.msg || statusText;
        if (resData.code === 1) {
          try {
            const decryptRes = getDecryptData(resData.data);
            return Promise.resolve(decryptRes || {});
          } catch (e) {
            return Promise.reject({
              msg: '解析错误',
              type: 'warning',
              description: '返回数据解析异常',
            });
          }
        } else if (/^1001/.test(resData.code)) {
          console.log('登录令牌异常');
          history.replace('/login');
        }
        return Promise.reject({
          msg: resData.code ? '温馨提示' : '请求错误',
          type: resData.code ? 'warning' : 'error',
          code: resData.code,
          description: errorMessage,
        });
      }
    } else if (response) {
      if (responseType === 'blob') {
        return Promise.reject({
          msg: '请求异常',
          type: 'error',
          description: '文件流获取异常',
        });
      } else {
        try {
          const resData = await response.clone().json();
          const { msg } = resData;
          if (msg) {
            return Promise.reject({
              msg: '系统异常',
              type: 'error',
              description: msg || '后台服务返回异常',
            });
          } else {
            return response;
          }
        } catch (e) {
          return response;
        }
      }
    }
    return response;
  },
];
